<script setup lang="ts">
	import { ref, onMounted, reactive } from "vue";
	import { formRules } from "./utils/rule";
	import { FormProps } from "./utils/types";
	import ReCol from "@/components/ReCol";
  import { baseUrlApi, baseOaApi } from "@/api/utils";
  import type { UploadProps } from "element-plus";
  import { message } from "@/utils/message";
  import { closeAllDialog } from "@/components/ReDialog/index"
  import { debounce } from "@pureadmin/utils";
  import { taskUpdateStatusApi } from "@/api/taskApi";
	const props = withDefaults(defineProps<FormProps>(), {
		formInline: () => ({
			title: "",
			status: 0,
			Id: 0,
		})
	});
	const ruleFormRef = ref();
	const newFormInline = ref(props.formInline);
	function getRef() {
		return ruleFormRef.value;
	}
	defineExpose({ getRef });
  const taskTypeSelect = [
    {id: 1, name: '合同审核'},
    {id: 2, name: '预收款核实'},
    {id: 3, name: '技术画图'},
    {id: 4, name: '下单采购'},
    {id: 5, name: '入库审核'},
    {id: 6, name: '组装生产'},
    {id: 7, name: '发货款核实'},
    {id: 8, name: '项目实施'},
    {id: 9, name: '项目验收'},
    {id: 10, name: '验收款质保金'},
  ]
  const isTwoOrSeven = (number) => {
    if(number === 1020000) {
      return false;
    }
    if(number === 1070000) {
      return false;
    }
    if(number === 1090000) {
      return false;
    }
    return true;
  };
  const statusSelect = reactive([
    // {id: 0, name: '未开始'},
    {id: 1, name: '进行中'},
    {id: 2, name: '挂起跳过',disabled: isTwoOrSeven(newFormInline.value?.taskType)},
    {id: 3, name: '已完成'},
    // {id: 4, name: '已关闭'},
  ])

  const actionUrl = baseUrlApi + "/uploadFile/upload";

  const fileList = ref([])
  const imgUrl = ref("");
  const handleAttachmentSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
  ) => {
    // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
    newFormInline.value.attachment = []

    for (let item of fileList.value) {
      if(item?.url) {
        newFormInline.value.attachment.push(item?.url)
      } else {
        newFormInline.value.attachment.push(baseOaApi + item?.response?.result?.path)
      }
    }
  };
  const beforeUpload = (file) => {
    const isContract = file.name.endsWith('.pdf') || file.name.endsWith('.doc') || file.name.endsWith('.docx'); // 检查文件类型是否为合同文件类型（例如：PDF, DOC, DOCX）
    const isLt500kb = file.size / 1024 < 500; // 检查文件大小是否小于500kb
    // if (!isContract) {
    //   message("文件格式不支持!", {
    //     type: "error"
    //   });
    //   return false; // 不允许上传非合同文件类型
    // }
    // if (!isLt500kb) {
    //   message("上传文件大小不能超过500kb!", {
    //     type: "error"
    //   });
    //   return false; // 不允许上传大于500kb的文件
    // }
    return true;
  }
  const uploadRef = ref()
  const submitUpload = () => {
    uploadRef.value!.submit()
  }
  onMounted(()=> {
    if(newFormInline.value.attachment && newFormInline.value.attachment.length > 0) {
      for (let item of newFormInline.value.attachment) {
        fileList.value.push({
          name: item,
          url: item
        })
      }

    } else {
      fileList.value = []
    }
  })
  const statusChange = (val) => {
    if(val === 3) {
      newFormInline.value.completeRate = 100
      newFormInline.value.receiptRatio = 100
    } else {
      newFormInline.value.completeRate = newFormInline.value.beforeCompleteRate
      newFormInline.value.receiptRatio = newFormInline.value.beforeReceiptRatio
    }
  }
  const receiptRatioLabel = (n) => {
    // if(n === 1020000) {
    //   return '预收款比例(%)'
    // }else if(n === 1070000) {
    //   return '发货款比例(%)'
    // }else if(n === 1090000) {
    //   return '到货款比例(%)'
    // } else if(n === 1120000) {
    //   return '验收款比例(%)'
    // }
    return '收款比例(%):'
  }
  const calculateWorkingHours = (s, e) => {
    const start = new Date(s);
    const end = new Date(e);
    let count = 0;
    const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
    for (let i = start; i <= end; i.setTime(i.getTime() + oneDay)) {
      const day = i.getDay();
      if (day !== 0 && day !== 6) { // 0 = Sunday, 6 = Saturday
        count++;
      }
    }
    return count*8;
  }
  const datePickerChange = (val) => {
    if(val) {
      newFormInline.value.expectHour = calculateWorkingHours(val[0], val[1])
    }
  }
  const openFile = (row) => {
    if(row.attachment && row.attachment.length > 0) {
      for (let item of row.attachment) {
        window.open(item.storageAddr, '_blank');
      }
    } else {
      message(`未上传文件`, { type: "error" });
    }

  }
  const closeDialog = () => {
    closeAllDialog()
  }

  const receiptChange = (val) => {
    if(val === 1) {
      newFormInline.value.receiptRatio = 100
    } else {
      newFormInline.value.receiptRatio = newFormInline.value.beforeReceiptRatio
    }
  }
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  const realTimeCroppered = () => {
    if(newFormInline.value.statusFlag) {
      message("该阶段已完成，请勿重复操作", {
        type: "error"
      });
      return
    }
    if(newFormInline.value.status !== 1 && !newFormInline.value.remarks) {
      message("请输入备注!", {
        type: "error"
      });
      return
    }

    if(newFormInline.value.taskType === 1100000 && newFormInline.value.attachment.length === 0 && newFormInline.value.status === 3) {
      message("请上传附件!", {
        type: "error"
      });
      return
    }
    let params = {
      taskId: newFormInline.value.taskId,
      taskType: newFormInline.value.taskType,
      projectId: newFormInline.value.projectId,
      status: newFormInline.value.status,
      remarks: newFormInline.value.remarks,
      attachment: newFormInline.value.attachment,
      completeRate: newFormInline.value.completeRate ? newFormInline.value.completeRate : 0,
      receiptRatio: newFormInline.value.receiptRatio,
      receiptFull: newFormInline.value.receiptFull,
      projectStatus: newFormInline.value.taskType === 1130000 ? 3 : null
    }
    taskUpdateStatusApi(cleanEmptyData(params)).then((res: any)=> {
      if(res?.code ===200) {
        message(`操作成功`, {
          type: "success"
        });
        closeDialog()
        newFormInline.value.fn()
      }
    }).catch(error => {
      message(error.response.data.msg ?? "操作失败,请联系管理员", {
        type: "error"
      });
    });
  }
  const saveSubmit = debounce(realTimeCroppered, 300);
</script>

<template>
	<el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="auto">
		<el-row :gutter="30" v-if="newFormInline.title ==='创建任务' || newFormInline.title ==='编辑任务'">
			<re-col :value="12" :xs="24" :sm="24">
				<el-form-item label="所属项目" prop="projectId">
					<el-select
					  v-model="newFormInline.projectId"
					  placeholder="请选择所属项目"
					  clearable
					>
					  <el-option
					    v-for="item in newFormInline.projectSelect"
					    :key="item.projectId"
					    :label="item.projectName"
					    :value="item.projectId"
					  />
					</el-select>
				</el-form-item>
			</re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="任务类型" prop="taskType">
          <el-select
            v-model="newFormInline.taskType"
            placeholder="请选择所属项目"
            clearable
          >
            <el-option
              v-for="item in taskTypeSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="指派用户" prop="assignedTo">
          <el-select
            v-model="newFormInline.assignedTo"
            placeholder="请选择指派用户"
            clearable
            multiple
          >
            <el-option
              v-for="item in newFormInline.userSelect"
              :key="item.userId"
              :label="item.username"
              :value="item.userId"
            />
          </el-select>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="计划日期" prop="rangePlanDate">
      		<el-date-picker
            v-model="newFormInline.rangePlanDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            @change="datePickerChange"
          />
      	</el-form-item>
      </re-col>
			<re-col :value="12" :xs="24" :sm="24">
				<el-form-item label="优先级" prop="priority">
					<el-input-number
						v-model="newFormInline.priority"
						class="!w-full"
						:min="0"
						:max="4"
						controls-position="right"
            :precision="0"
					  />
				</el-form-item>
			</re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="预计小时" prop="expectHour">
      		<el-input-number
      			v-model="newFormInline.expectHour"
      			class="!w-full"
      			:min="0"
      			:max="9999"
      			controls-position="right"
            :precision="0"
      		  />
      	</el-form-item>
      </re-col>
			<re-col :value="12" :xs="24" :sm="24">
				<el-form-item label="描述" prop="description">
					<el-input v-model="newFormInline.description" clearable placeholder="请输入描述" />
				</el-form-item>
			</re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="关键词" prop="keyword">
      		<el-input v-model="newFormInline.keyword" clearable placeholder="请输入关键词" />
      	</el-form-item>
      </re-col>

      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="抄送给用户" prop="assignedExtraTo">
      		<el-select
      		  v-model="newFormInline.assignedExtraTo"
      		  placeholder="请选择抄送用户"
      		  clearable
      		  multiple
      		>
      		  <el-option
      		    v-for="item in newFormInline.userSelect"
      		    :key="item.userId"
      		    :label="item.username"
      		    :value="item.userId"
      		  />
      		</el-select>
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="完成比例" prop="completeRate">
      		<el-input-number
      			v-model="newFormInline.completeRate"
      			class="!w-full"
      			:min="0"
      			:max="100"
      			controls-position="right"
            :precision="0"
      		  />
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="附件" required>
      		<!-- <el-upload
      		  ref="uploadRef"
      		  :action="actionUrl"
      		  :on-success="handleAttachmentSuccess"
      		  v-model:file-list="fileList"
      		  :before-upload="beforeUpload"
      		  multiple>
      		  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传附件</el-button>
      		</el-upload> -->
      	</el-form-item>
      </re-col>
		</el-row>
    <el-row :gutter="30" v-if="newFormInline.title ==='执行任务'">
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="所属项目:" prop="projectName">
          <!-- <el-input v-model="newFormInline.projectName" disabled clearable placeholder="请输入所属项目" /> -->
          {{newFormInline.projectName || '--'}}
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="已执行阶段:" prop="currentTaskTypeName">
          <!-- <el-input v-model="newFormInline.currentTaskTypeName" disabled clearable placeholder="--" /> -->
          {{newFormInline.currentTaskTypeName || '--'}}
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="待执行阶段:" prop="taskTypeName">
          <!-- <el-input v-model="newFormInline.taskTypeName" disabled clearable placeholder="--" /> -->
          {{newFormInline.taskTypeName || '--'}}
      	</el-form-item>
      </re-col>

      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="审核状态:" prop="status">
          <el-select
            v-model="newFormInline.status"
            placeholder="请选择审核状态"
            clearable
            @change="statusChange"
            :disabled="newFormInline.statusFlag"
          >
            <el-option
              v-for="item in statusSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            />
          </el-select>
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="完成比例(%):" >
          <el-input-number
          	v-model="newFormInline.completeRate"
          	class="!w-full"
          	:min="0"
          	:max="100"
          	controls-position="right"
            :precision="0"
            :disabled="newFormInline.statusFlag || newFormInline.status === 3"
            :step="5"
            />
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24" v-if="newFormInline.taskType === 1020000 || newFormInline.taskType === 1070000 || newFormInline.taskType === 1090000 || newFormInline.taskType === 1120000">
      	<el-form-item :label="receiptRatioLabel(newFormInline.taskType)" prop="receiptRatio">
          <el-input-number
          	v-model="newFormInline.receiptRatio"
          	class="!w-full"
          	:min="0"
          	:max="100"
          	controls-position="right"
            :disabled="newFormInline.statusFlag || newFormInline.status === 3 || newFormInline.receiptFull === 1"
            :precision="0"
            :step="10"
            />
      	</el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24" v-if="newFormInline.taskType === 1020000 || newFormInline.taskType === 1070000 || newFormInline.taskType === 1090000 || newFormInline.taskType === 1120000">
      	<el-form-item label="收款标识:" prop="receiptFull">
          <!-- <el-select
            v-model="newFormInline.receiptFull"
            placeholder="请选择收款标识"
            clearable
          >
            <el-option label="未结清" :value="0"/>
            <el-option label="已结清" :value="1"/>
          </el-select> -->
          <el-radio-group v-model="newFormInline.receiptFull" @change="receiptChange">
            <el-radio :value="0">未结清</el-radio>
            <el-radio :value="1">已结清</el-radio>
          </el-radio-group>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="备注:" prop="remarks">
          <el-input v-model="newFormInline.remarks":disabled="newFormInline.statusFlag" type="textarea" :rows="2" clearable placeholder="请输入备注" />
          <div v-if="newFormInline.taskType === 8" style="color: red;">提示：请在备注中输入发货时间</div>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="附件:">
      		<el-upload
      		  ref="uploadRef"
      		  :action="actionUrl"
      		  :on-success="handleAttachmentSuccess"
      		  v-model:file-list="fileList"
      		  :before-upload="beforeUpload"
            :disabled="newFormInline.statusFlag"
            class="!w-full"
            drag
      		  multiple>
            <el-button link type="primary" @click="submitUpload">上传附件</el-button>
            <template #tip v-if="newFormInline.currentTaskType === 9 && newFormInline.status === 3">
              <div class="el-upload__tip text-red">
                请上传客户盖章签字的验收单附件
              </div>
            </template>
      		</el-upload>
      	</el-form-item>
      </re-col>
      <div class="flex mt-[20px] pr-[15px]" style="justify-content: right; width: 100%;">

        <el-button type="success" text bg v-if="newFormInline.taskType === 1130000" @click="saveSubmit">
          确认并完成项目
        </el-button>
        <el-button text bg @click="closeDialog">
          取消
        </el-button>
        <el-button type="primary" text bg @click="saveSubmit">
          确定
        </el-button>

      </div>
    </el-row>
    <template v-if="newFormInline.title ==='批量执行'">
      <el-form-item label="审核状态" prop="status">
        <el-select
          v-model="newFormInline.status"
          placeholder="请选择审核状态"
        >
          <el-option
            label="已完成"
            :value="3"
          />
        </el-select>
      </el-form-item>
      <div class="flex-bc">
        <el-form-item label="完成比例(%):" required style="width: 45%;">
          <el-input-number
          	v-model="newFormInline.completeRate"
          	class="!w-full"
          	:min="0"
          	:max="100"
            :disabled="true"
          	controls-position="right"
            :precision="0"
            :step="5"
            />
        </el-form-item>
        <el-form-item label="收款比例(%):" required style="width: 45%;" v-if="newFormInline.flag">
          <el-input-number
          	v-model="newFormInline.receiptRatio"
          	class="!w-full"
          	:min="0"
          	:max="100"
            :disabled="true"
          	controls-position="right"
            :precision="0"
            :step="10"
            />
        </el-form-item>
      </div>

      <el-form-item label="附件">
      	<el-upload
      	  ref="uploadRef"
      	  :action="actionUrl"
      	  :on-success="handleAttachmentSuccess"
      	  v-model:file-list="fileList"
      	  :before-upload="beforeUpload"
          class="!w-full"
          drag
      	  multiple>
          <el-button link type="primary" @click="submitUpload">上传附件</el-button>
      	</el-upload>
      </el-form-item>
      <el-form-item label="备注" required>
        <el-input v-model="newFormInline.remarks" type="textarea" :rows="2" clearable placeholder="请输入备注" />
      </el-form-item>
    </template>
	</el-form>
  <template v-if="newFormInline.title ==='日志'">
    <el-table :data="newFormInline.record" style="width: 100%;height: 500px;margin-bottom: 20px;" ref="tableRef" row-key="projectId" :header-cell-style="{background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)'}" show-overflow-tooltip>
      <el-table-column label="所属项目" prop="remarks" :minWidth="180">
        <template #default="{row}">
          {{newFormInline.projectName}}
        </template>
      </el-table-column>
      <el-table-column label="任务阶段" prop="remarks" :minWidth="120">
        <template #default="{row}">
          {{newFormInline.taskTypeName}}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="operateType" :minWidth="120">
        <template #default="{row}">
          <span v-if="row.operateType === 0">未开始</span>
          <span v-else-if="row.operateType === 1">进行中</span>
          <span v-else-if="row.operateType === 2">挂起跳过</span>
          <span v-else-if="row.operateType === 3">已完成</span>
          <span v-else-if="row.operateType === 4">已关闭</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" prop="operateName" :minWidth="120"/>
      <el-table-column label="完成比例(%)" prop="completeRate" :minWidth="120"/>
      <el-table-column label="收款比例(%)" prop="receiptRatio" :minWidth="120">
        <template #default="{row}">
          <span v-if="row.receiptRatio !== null">{{row.receiptRatio}}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" prop="operateTime" :minWidth="180"/>

      <el-table-column label="备注" prop="remarks" :minWidth="120"></el-table-column>

      <el-table-column label="附件" prop="planStartDate">
        <template #default="{row}">
          <div class="flex">
            <el-button @click="openFile(row)" size="small">查看</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex;justify-content: right;">
      <el-button type="primary" @click="closeDialog">关闭</el-button>
    </div>
  </template>
</template>
<style scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
  .text-red {
    color: #f87171;
  }
</style>
